Private fields in JavaScript classes

Firefox version 90 brings private field in ES6 classes, let's walk through with an example.

We will be creating a class for a Person and will be hiding the property age.

class Person {
  #age;
  constructor(age) {
    this.#age = age;
  }
  get age() {
    return this.#age;
  }
  set age(value) {
    this.#age = value;
  }
}

const person = new Person(18);

console.log(person.age);
person.age = 19;
console.log(person.age);

As you can see in above example we declared variable #age which is private, if you try to access p.#age you'll get an error like this Uncaught SyntaxError: reference to undeclared private field or method #age

Let's implement inheritance and see,

class Men extends Person {
  constructor(age) {
    super(age);
  }
  wishForBirthday() {
    console.log("Happy Birthday!");
    this.age += 1;
  }
}

const men = new Men(18);
men.wishForBirthday();
console.log(men.age);

As you can see in above inheritance, Inherited class can't directly access #age since it's private. If you still try to refer age using #age you'll get an error Uncaught SyntaxError: reference to undeclared private field or method #age

That's all folks, More read from Mozilla Hacks

Copyright 2020-2021 nerding_it ( HTML).
Last updated 2021-07-30 Fri 19:07.
Built with Emacs 27.2 (Org mode 9.4.4).
Subscribe to Weekly News Letter
We'll never share your email with anyone else.